package com.movitech.mobile.cz.base.purchase.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.movitech.mobile.cz.base.common.aop.ServiceThrowable;
import com.movitech.mobile.cz.base.common.util.*;
import com.movitech.mobile.cz.base.modules.config.PurchaseCommonEnum;
import com.movitech.mobile.cz.base.modules.config.PurchasePlanStatusEnum;
import com.movitech.mobile.cz.base.modules.controller.RestReturnResult;
import com.movitech.mobile.cz.base.purchase.bizvo.ConfirmedProjectResponseVO;
import com.movitech.mobile.cz.base.purchase.bizvo.SpecialPurchasePlanListResponseVO;
import com.movitech.mobile.cz.base.purchase.entity.PContactPlan;
import com.movitech.mobile.cz.base.purchase.entity.PSpecialPurchasePlan;
import com.movitech.mobile.cz.base.purchase.entity.ext.ExtPSpecialPurchasePlan;
import com.movitech.mobile.cz.base.purchase.entity.ext.PSpecialPurchasePlanFindRequest;
import com.movitech.mobile.cz.base.purchase.entity.ext.PSpecialPurchasePlanSaveRequestVO;
import com.movitech.mobile.cz.base.purchase.mapper.PSpecialPurchasePlanMapper;
import com.movitech.mobile.cz.base.purchase.mapper.WFlowFormMapper;
import com.movitech.mobile.cz.base.purchase.mapper.ext.ExtPSpecialPurchasePlanMapper;
import com.movitech.mobile.cz.base.purchase.service.PContactPlanService;
import com.movitech.mobile.cz.base.purchase.service.PPlanChangesService;
import com.movitech.mobile.cz.base.purchase.service.PSpecialPurchasePlanService;
import com.movitech.mobile.cz.base.util.UserUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 专项采购计划 服务实现类
 * </p>
 *
 * @author Movitech Mobile
 * @since 2018-03-08
 */
@Service
public class PSpecialPurchasePlanServiceImpl extends ServiceImpl<PSpecialPurchasePlanMapper, PSpecialPurchasePlan> implements PSpecialPurchasePlanService {

    private final static Logger logger = Logger.getLogger(PSpecialPurchasePlanServiceImpl.class);

    @Autowired
    private ExtPSpecialPurchasePlanMapper extPSpecialPurchasePlanMapper;

    @Autowired
    private PContactPlanService pContactPlanService;

    @Autowired
    private PSpecialPurchasePlanMapper pSpecialPurchasePlanMapper;

    @Autowired
    private WFlowFormMapper wFlowFormMapper;

    @Autowired
    private PPlanChangesService pPlanChangesService;

    @Override
    public PageCode findSpecialPurchasePlanList(PSpecialPurchasePlanFindRequest pSpecialPurchasePlan) throws Exception {

        try {

            if (pSpecialPurchasePlan.getPageFlag() == 0) {//不分页
                pSpecialPurchasePlan.setPageSize(10);
            }

            PageCode pageCode = new PageCode(pSpecialPurchasePlan.getPageNumber(), pSpecialPurchasePlan.getPageSize());
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("currentRecordNum", (pageCode.getPageNo() - 1) * pageCode.getPageSize());
            map.put("pageSize", pageCode.getPageSize());
            map.put("pageFlag", pSpecialPurchasePlan.getPageFlag());

            map.put("regionalCompanyId", pSpecialPurchasePlan.getRegionalCompanyId());
            map.put("projectId", pSpecialPurchasePlan.getProjectId());
            map.put("purchaseItemName", pSpecialPurchasePlan.getPurchaseItemName());
            map.put("purchaseClassification", pSpecialPurchasePlan.getPurchaseClassification());
            map.put("procuringEntity", pSpecialPurchasePlan.getProcuringEntity());
            map.put("purchaseType", pSpecialPurchasePlan.getPurchaseType());
//            map.put("techManageRequiredCmpTimeStart", pSpecialPurchasePlan.getTechManageRequiredCmpTimeStart());
//            map.put("techManageRequiredCmpTimeEnd", pSpecialPurchasePlan.getTechManageRequiredCmpTimeEnd());
            map.put("planPurchasePlanCmpTimeStart", pSpecialPurchasePlan.getPlanPurchasePlanCmpTimeStart());
            map.put("planPurchasePlanCmpTimeEnd", pSpecialPurchasePlan.getPlanPurchasePlanCmpTimeEnd());
            map.put("planCalibrationCmpTimeStart", pSpecialPurchasePlan.getPlanCalibrationCmpTimeStart());
            map.put("planCalibrationCmpTimeEnd", pSpecialPurchasePlan.getPlanCalibrationCmpTimeEnd());
            map.put("planStatus", pSpecialPurchasePlan.getPlanStatus());

            Integer count = extPSpecialPurchasePlanMapper.findSpecialPurchasePlanListCount(map);
            pageCode.setCount(count == null ? 0 : count);
            List<ExtPSpecialPurchasePlan> ls = extPSpecialPurchasePlanMapper.findSpecialPurchasePlanList(map);

            List<SpecialPurchasePlanListResponseVO> result = null;
            if (ls != null) {
                result = ListObjCopyUtil.copyTo(ls, SpecialPurchasePlanListResponseVO.class);
            }

            pageCode.setList(result);
            return pageCode;

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("==============findSpecialPurchasePlanList=====e:======" + e.getMessage());
            throw new Exception(e);
        }

    }

    @Override
    public void updateChangeTime(String[] planIds) {
        extPSpecialPurchasePlanMapper.updateChangeTime(planIds);
    }

    @Override
    public List<PSpecialPurchasePlan> findByIds(String[] ids) {
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.in("id", ids);
        return selectList(entityWrapper);
    }

    @Override
    public List<SpecialPurchasePlanListResponseVO> findSpecialPurchasePlanListNoPage(PSpecialPurchasePlanFindRequest pSpecialPurchasePlan) {

        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("pageFlag", 0);

            map.put("regionalCompanyId", pSpecialPurchasePlan.getRegionalCompanyId());
            map.put("projectId", pSpecialPurchasePlan.getProjectId());
            map.put("purchaseItemName", pSpecialPurchasePlan.getPurchaseItemName());
            map.put("purchaseClassification", pSpecialPurchasePlan.getPurchaseClassification());
            map.put("procuringEntity", pSpecialPurchasePlan.getProcuringEntity());
            map.put("purchaseType", pSpecialPurchasePlan.getPurchaseType());
//            map.put("techManageRequiredCmpTimeStart", pSpecialPurchasePlan.getTechManageRequiredCmpTimeStart());
//            map.put("techManageRequiredCmpTimeEnd", pSpecialPurchasePlan.getTechManageRequiredCmpTimeEnd());
            map.put("planPurchasePlanCmpTimeStart", pSpecialPurchasePlan.getPlanPurchasePlanCmpTimeStart());
            map.put("planPurchasePlanCmpTimeEnd", pSpecialPurchasePlan.getPlanPurchasePlanCmpTimeEnd());
            map.put("planCalibrationCmpTimeStart", pSpecialPurchasePlan.getPlanCalibrationCmpTimeStart());
            map.put("planCalibrationCmpTimeEnd", pSpecialPurchasePlan.getPlanCalibrationCmpTimeEnd());
            map.put("planStatus", pSpecialPurchasePlan.getPlanStatus());

            List<ExtPSpecialPurchasePlan> ls = extPSpecialPurchasePlanMapper.findSpecialPurchasePlanList(map);

            List<SpecialPurchasePlanListResponseVO> result = null;
            if (ls != null) {
                result = ListObjCopyUtil.copyTo(ls, SpecialPurchasePlanListResponseVO.class);
            }
            return result;

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("==============findSpecialPurchasePlanList=====e:======" + e.getMessage());
        }
        return null;
    }

    @Override
    public ExtPSpecialPurchasePlan getSpecialPurchasePlanById(String specialPurchasePlanId) {
        ExtPSpecialPurchasePlan specialPurchasePlan = extPSpecialPurchasePlanMapper.getSpecialPurchasePlanById(specialPurchasePlanId);
        return specialPurchasePlan;
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public RestReturnResult saveSpecialPurchasePlan(PSpecialPurchasePlanSaveRequestVO pSpecialPurchasePlanSaveRequestVO) throws RuntimeException {
        RestReturnResult<Object> restReturnResult = RestReturnResult.error();

        try {
            String userId = UserUtils.getCurrentUserId();

            if (pSpecialPurchasePlanSaveRequestVO != null) {

                Double planBudgetPrices = 0.00d;

                if (StringUtils.isNotBlank(pSpecialPurchasePlanSaveRequestVO.getPSpecialPurchasePlanId())) {//update

                    PSpecialPurchasePlan pSpecialPurchasePlanDB = this.selectById(pSpecialPurchasePlanSaveRequestVO.getPSpecialPurchasePlanId());

                    if (pSpecialPurchasePlanDB != null) {

                        String contactPlanIdDB = pSpecialPurchasePlanDB.getContactPlanId() == null ? "" : pSpecialPurchasePlanDB.getContactPlanId();
                        String contactPlanIdRequest = pSpecialPurchasePlanSaveRequestVO.getContactPlanId() == null ? "" : pSpecialPurchasePlanSaveRequestVO.getContactPlanId();
                        String[] contactPlanIdDBArr = contactPlanIdDB.split(",");
                        String[] contactPlanIdRequestArr = contactPlanIdRequest.split(",");
                        List<String> addedContactPlanIdList = new ArrayList<String>();
                        List<String> deletedContactPlanIdList = new ArrayList<String>();
                        if (contactPlanIdDBArr != null && contactPlanIdRequestArr != null) {
                            if (!(contactPlanIdDBArr.length == 0 && contactPlanIdRequestArr.length == 0)) {

                                //原先没有，全部新增
                                if (contactPlanIdRequestArr.length > 0) {
                                    addedContactPlanIdList = Arrays.asList(contactPlanIdRequestArr);
                                }

                                //原先有，全部删除
                                if (contactPlanIdDBArr.length > 0) {
                                    deletedContactPlanIdList = Arrays.asList(contactPlanIdDBArr);
                                }

//    							//其他情况
//    							if(contactPlanIdDBArr.length > 0 && contactPlanIdRequestArr.length > 0){
//    								List<String> contactPlanIdRequestList = Arrays.asList(contactPlanIdRequestArr);
//    								List<String> contactPlanIdDBList = Arrays.asList(contactPlanIdDBArr);
//    								for(String contactPlanId : contactPlanIdDBArr){
//
//    									if(!contactPlanIdRequestList.contains(contactPlanId)){
//    										deletedContactPlanIdList.add(contactPlanId);
//    									}
//
//    								}
//
//    								for(String contactPlanId : contactPlanIdRequestArr){
//
//    									if(!contactPlanIdDBList.contains(contactPlanId)){
//    										addedContactPlanIdList.add(contactPlanId);
//    									}
//
//    								}
//    							}
                                if (deletedContactPlanIdList != null && deletedContactPlanIdList.size() > 0) {
                                    List<PContactPlan> unGeneratedList = pContactPlanService.selectBatchIds(deletedContactPlanIdList);

                                    if (unGeneratedList != null && unGeneratedList.size() > 0) {
                                        for (PContactPlan pContactPlan : unGeneratedList) {
                                            pContactPlan.setPlanStatus(CommonConstants.GENERATED_NO);//回滚成为未生成
                                            pContactPlan.setPurchaseItemName(null);//回滚成为未生成
                                            pContactPlan.setBaseFeilds(userId, null, CommonConstants.NO_INTEGER, false);
                                        }

                                        pContactPlanService.updateBatchById(unGeneratedList);
                                    }

                                }

                                if (addedContactPlanIdList != null && addedContactPlanIdList.size() > 0) {
                                    List<PContactPlan> generatedList = pContactPlanService.selectBatchIds(addedContactPlanIdList);

                                    if (generatedList != null && generatedList.size() > 0) {
                                        for (PContactPlan pContactPlan : generatedList) {
                                            pContactPlan.setPlanStatus(CommonConstants.GENERATED_YES);//专项采购计划已生成
                                            pContactPlan.setPurchaseItemName(pSpecialPurchasePlanDB.getId());//专项采购计划已生成
                                            pContactPlan.setBaseFeilds(userId, null, CommonConstants.NO_INTEGER, false);
                                            if (pContactPlan.getPlanBudgetPrices() != null) {
                                                planBudgetPrices += pContactPlan.getPlanBudgetPrices();
                                            }
                                        }

                                        pContactPlanService.updateBatchById(generatedList);
                                    }
                                }


                            }
                        }


                        BeanUtils.copyProperties(pSpecialPurchasePlanSaveRequestVO, pSpecialPurchasePlanDB);
                        /*PContactPlan contactPlan = pContactPlanService.selectById(pSpecialPurchasePlanSaveRequestVO.getContactPlanId());
                        if (contactPlan != null) {
                            pSpecialPurchasePlanDB.setPlanBudgetPrices(contactPlan.getPlanBudgetPrices());
                            pSpecialPurchasePlanDB.setPlanBudgetTime(contactPlan.getPlanBudgetTime());
                        } else {
                            pSpecialPurchasePlanDB.setPlanBudgetPrices(null);
                            pSpecialPurchasePlanDB.setPlanBudgetTime(null);
                            //throw new RuntimeException("在合约规划不存", new ServiceThrowable());
                        }*/
                        pSpecialPurchasePlanDB.setPlanBudgetPrices(planBudgetPrices.doubleValue());
                        pSpecialPurchasePlanDB.setPlanStatus(PurchasePlanStatusEnum.PURCHASE_PLAN_STATUS_1.getCode()); //待确认
                        updateAllColumnById(pSpecialPurchasePlanDB);
                        //this.updatePSpecialPurchasePlan(pSpecialPurchasePlanDB);

                        restReturnResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, "专项采购计划修改成功");
                    } else {
                        restReturnResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[2], CommonConstants.ERROR_DESCS[2]);
                    }

                } else {//insert

                    PSpecialPurchasePlan pSpecialPurchasePlan = new PSpecialPurchasePlan();
                    BeanUtils.copyProperties(pSpecialPurchasePlanSaveRequestVO, pSpecialPurchasePlan);

                    PContactPlan contactPlan = pContactPlanService.selectById(pSpecialPurchasePlanSaveRequestVO.getContactPlanId());
                    if (contactPlan != null) {
                        pSpecialPurchasePlan.setPlanBudgetPrices(contactPlan.getPlanBudgetPrices());
                        pSpecialPurchasePlan.setPlanBudgetTime(contactPlan.getPlanBudgetTime());
                    } else {
                        //throw new RuntimeException("合约规划不存在", new ServiceThrowable());
                    }
                    pSpecialPurchasePlan.setPurchasePlanConfirmTime(pSpecialPurchasePlan.getPlanPurchasePlanCmpTime());
                    pSpecialPurchasePlan.setPlanCalibrationConfirmTime(pSpecialPurchasePlan.getPlanCalibrationCmpTime());
                    pSpecialPurchasePlan.setPlanStatus(PurchasePlanStatusEnum.PURCHASE_PLAN_STATUS_1.getCode()); //待确认


                    boolean flag = this.addPSpecialPurchasePlan(pSpecialPurchasePlan);

                    //更新合约规划状态
                    if (flag && StringUtils.isNotBlank(pSpecialPurchasePlanSaveRequestVO.getContactPlanId())) {

                        String[] contactPlanIdArr = pSpecialPurchasePlanSaveRequestVO.getContactPlanId().split(",");
                        List<String> contactPlanIdList = Arrays.asList(contactPlanIdArr);

                        List<PContactPlan> pContactPlanList = pContactPlanService.selectBatchIds(contactPlanIdList);

                        if (pContactPlanList != null && pContactPlanList.size() > 0) {

                            for (PContactPlan pContactPlan : pContactPlanList) {
                                pContactPlan.setPlanStatus(CommonConstants.GENERATED_YES);//专项采购计划已生成
                                pContactPlan.setPurchaseItemName(pSpecialPurchasePlan.getId());
                                pContactPlan.setBaseFeilds(userId, null, CommonConstants.NO_INTEGER, false);
                                if (pContactPlan.getPlanBudgetPrices() != null) {
                                    planBudgetPrices += pContactPlan.getPlanBudgetPrices();
                                }
                            }


                            boolean contactPlanFlag = pContactPlanService.updateBatchById(pContactPlanList);

                            //更新计划合约金额
                            pSpecialPurchasePlan.setPlanBudgetPrices(planBudgetPrices);
                            this.updatePSpecialPurchasePlan(pSpecialPurchasePlan);

                            restReturnResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, "专项采购计划新增成功");
                        } else {
                            restReturnResult = new RestReturnResult<Object>(CommonConstants.FAIL, "合约规划不存在");
                            throw new Exception("合约规划不存在", new ServiceThrowable());
                        }

                    } else {
                        //restReturnResult = new RestReturnResult<Object>(CommonConstants.FAIL, "专项采购计划生成失败");
                    }
                    restReturnResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, "专项采购计划新增成功");
                }

            } else {
                restReturnResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[4], CommonConstants.ERROR_DESCS[4]);
            }

//    		pContactPlanService.insertOrUpdateSpecialPurchasePlan(specialPurchasePlanSaveRequest.getContactPlan());
//
//    		saveOrUpdateSpecialPurchasePlan(specialPurchasePlanSaveRequest.getSpecialPurchasePlan());

            return restReturnResult;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("===============saveSpecialPurchasePlan===e===========:" + e);
            throw new RuntimeException(e.getMessage(), e.getCause());
        }

    }


    @Override
    public List<ExtPSpecialPurchasePlan> selectPSpPlanUnConfirmProjects() {
        return extPSpecialPurchasePlanMapper.getPSpPlanUnConfirmProjects();
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void deleteById(String id) {
        try {
            PSpecialPurchasePlan pspp = selectById(id);
            if (pspp.getPlanStatus() != PurchasePlanStatusEnum.PURCHASE_PLAN_STATUS_1.getCode() &&
                    pspp.getPlanStatus() != PurchasePlanStatusEnum.PURCHASE_PLAN_STATUS_3.getCode()) {
                throw new RuntimeException("当前不是可删除状态", new ServiceThrowable());
            }
            String contactPlanIdstr = pspp.getContactPlanId();
            pspp = new PSpecialPurchasePlan();
            pspp.setId(id);
            pspp.setPlanBudgetPrices(null);
            pspp.setDelFlag(CommonConstants.YES_INTEGER);
            pspp.setUpdateBy(UserUtils.getCurrentUserId());
            pspp.setUpdateDate(DateUtils.getNow());
            updateById(pspp);
            if (StringUtils.isNotEmpty(contactPlanIdstr)) {
                String[] contactPlanIds = contactPlanIdstr.split(",");
                for (String contactPlanId : contactPlanIds) {
                    PContactPlan pcp = new PContactPlan();
                    pcp.setUpdateBy(UserUtils.getCurrentUserId());
                    pcp.setUpdateDate(DateUtils.getNow());
                    pcp.setUpdateDate(DateUtils.getNow());
                    pcp.setId(contactPlanId);
                    pcp.setPlanStatus(PurchaseCommonEnum.CONTANT_PLANS_STATUS_NO.getCode());
                    pContactPlanService.updateById(pcp);
                }
            }
        } catch (Exception e) {
//            reuslt = new RestReturnResult<Object>(CommonConstants.FAIL, id,
//                    CommonConstants.ERROR_CODES[0],e.getMessage());
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }


    @Override
    public String getNewPlansByProjectId(String project_id) {
        return extPSpecialPurchasePlanMapper.getNewPlansByProjectId(project_id);
    }

    @Override
    public boolean addPSpecialPurchasePlan(PSpecialPurchasePlan pSpecialPurchasePlan) {

        if (pSpecialPurchasePlan != null) {

            if (StringUtils.isBlank(pSpecialPurchasePlan.getId())) {
                pSpecialPurchasePlan.setId(IdGenUtils.uuid());
            }

            String userId = UserUtils.getCurrentUserId();
            Date createDate = new Date();
            pSpecialPurchasePlan.setCreateBy(userId);
            pSpecialPurchasePlan.setCreateDate(createDate);
            pSpecialPurchasePlan.setUpdateBy(userId);
            pSpecialPurchasePlan.setUpdateDate(createDate);
            pSpecialPurchasePlan.setDelFlag(CommonConstants.NO_INTEGER);

            int i = baseMapper.insert(pSpecialPurchasePlan);

            return i > 0;

        }

        return false;
    }

    @Override
    public boolean updatePSpecialPurchasePlan(PSpecialPurchasePlan pSpecialPurchasePlan) {

        if (pSpecialPurchasePlan != null && StringUtils.isNotBlank(pSpecialPurchasePlan.getId())) {

            String userId = UserUtils.getCurrentUserId();
            Date updateDate = new Date();
            pSpecialPurchasePlan.setUpdateBy(userId);
            pSpecialPurchasePlan.setUpdateDate(updateDate);
            int i = baseMapper.updateById(pSpecialPurchasePlan);
            return i > 0;

        }

        return false;
    }

    /**
     * 获取专项采购计划确认项目列表
     */
    @Override
    public RestReturnResult getConfirmedProjects(String regionalCompanyId) {
        RestReturnResult<Object> restReturnResult = RestReturnResult.error();
        try {
            List<ExtPSpecialPurchasePlan> ls = extPSpecialPurchasePlanMapper.getConfirmedProjects(regionalCompanyId);
            List<ConfirmedProjectResponseVO> result = new ArrayList<ConfirmedProjectResponseVO>();
            if (ls != null) {
                result = ListObjCopyUtil.copyTo(ls, ConfirmedProjectResponseVO.class);
            }

            restReturnResult = new RestReturnResult(CommonConstants.SUCCESS, result);

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("===========getConfirmedProjects===========e:===" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e.getCause());
        }

        return restReturnResult;
    }
}
